package com.lincoln.framework;

import com.lincoln.framework.interfaces.BaseDeviceInfo;
import com.lincoln.framework.interfaces.BaseProtocol;
import com.lincoln.framework.interfaces.NettyContextBean;

/**
 * 服务器上下文
 *
 * @author lincoln
 * @date 2018/11/30
 */
public class AbstractThreadLocalNettyContextBean implements NettyContextBean {
    private static ThreadLocal<BaseDeviceInfo> deviceInfoThreadLocal = new ThreadLocal<>();
    private static ThreadLocal<BaseProtocol> protocolThreadLocal = new ThreadLocal<>();

    /**
     * 获取当前设备
     *
     * @return
     */
    @Override
    public BaseDeviceInfo getDevice() {
        BaseDeviceInfo deviceInfo = deviceInfoThreadLocal.get();
        //第一次请求
        if (deviceInfo == null) {
            try {
                deviceInfo = NettyServer.getNettyServer().getDeviceInfo().newInstance();
                deviceInfoThreadLocal.set(deviceInfo);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return deviceInfo;
    }

    /**
     * 设置当前设备
     *
     * @param deviceInfo
     * @return
     */
    @Override
    public boolean setDevice(BaseDeviceInfo deviceInfo) {
        try {
            deviceInfoThreadLocal.set(deviceInfo);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取当前帧
     *
     * @return
     */
    @Override
    public BaseProtocol getProtocol() {
        return protocolThreadLocal.get();
    }

    /**
     * 设置当前帧
     *
     * @param protocol
     * @return
     */
    @Override
    public boolean setProtocol(BaseProtocol protocol) {
        try {
            protocolThreadLocal.set(protocol);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean remove() {
        deviceInfoThreadLocal.remove();
        protocolThreadLocal.remove();
        return true;
    }
}
